package oleg.match; 

/**
 * Copyright 2008 Oleg Frenkel
 *
 * This file is part of PerfectSearch.
 *
 * PerfectSearch is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * PerfectSearch is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PerfectSearch.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.*;

public class Cache
{
  static private Cache instance = new Cache();

  private Hashtable cache = new Hashtable();
  private int clearCount = 0;

  // This is a singleton
  private Cache() {}

  static public Cache instance() {
    return instance;
  }

  public void put(Object key, Object value) {
    Runtime rt = Runtime.getRuntime();
    long freeMem = rt.freeMemory();
    long totalMem = rt.totalMemory();
    if (10 * freeMem < 2 * totalMem) {
      // Free memory is less than 20% of total memory, purge cache
      cache.clear();
      rt.gc();
      clearCount++;
      return;
    }

    cache.put(key, value);
  }

  public void clear() {
    cache.clear();
  }

  public Object get(Object key) {
    return cache.get(key);
  }

  public int getClearCount() {
    return clearCount;
  }

  
}